package com.wang.controller.api;

import com.wang.controller.utils.SmsUtil;
import com.wang.utils.ConstantUtil;
import com.wang.utils.ResponseEnum;
import com.wang.utils.ResponseUtil;
import com.wang.utils.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Classname ApiSmsController
 * @Description TODO
 * @Date 2024/9/30 9:53
 * @Created by pc
 */
@RestController
@Slf4j
@RequestMapping("/api/sms")
@Api(value = "发送短信",tags = "ApiSmsController")
public class ApiSmsController {

    @Resource
    private VerifyCodeUtil codeUtil;

    @Resource
    private SmsUtil smsUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping(value = "/sendVerifyCode")
    @ApiOperation(value = "发送短信",notes = "发送四位验证码")
    @ApiImplicitParam(name = "phone",value = "用户联系方式",required = true,dataType = "String")
    public ResponseUtil sendVerifyCode(String phone){
        // 生成验证码
        String code = codeUtil.getCode();
        // 发送短信
        // smsUtil.sendVerifyCode(phone,code);
        System.out.println(phone+"-"+code);
        // 存redis
        // 生成一个uuid 作为存入redis的key  redis中的value  phone-code
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        // 设置存入redis的key 是 uuid  值是 phone-code  电话-验证码
        stringRedisTemplate.opsForValue().set(uuid,phone+"-"+code);
        // 设置这个uuid的过期时间是5分钟
        stringRedisTemplate.expire(uuid, ConstantUtil.VERIFY_CODE_TIMEOUT, TimeUnit.MINUTES);
        // 发送完短信验证码 需要将uuid返回给前台 等待用户校验的时候通过这个uuid去查询验证码和电话是否匹配
        Map<String, Object> map = new HashMap<>();
        map.put("uuid",uuid);
        return ResponseUtil.get(ResponseEnum.SMS_VERIFY_4_CODE_SUCCESS,map);
    }

}
